/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.*;
import java.awt.EventQueue;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.CalcularTotalAlquiler;
import logica.MailSender;

/**
 *
 * @author Smuggler
 */
public class VistaNuevaReserva extends JPanel {

    private Logs logs;
    private static int cantidadReservasCreadas = 0;
    private List clienteLista;
    private JFrame frame;
    private int limite = 8;
    String tipoAlquiler = "R";
    entities.Alquileres alquilerActual;
    private int nroDep;
    private Date fechaArriboRecibida;
    private Date fechaPartidaRecibida;
    private UnidadesAlojamiento unidadAlojamientoReservaActual;
    private static Clientes cliente;
    private Usuarios usuario;
    public static Moneda monedaPorDefecto;

    private VistaNuevaReserva(Integer nroDepto, Date fechaArribo, Date fechaPartida, JFrame frame, Usuarios usuario) {
        this.nroDep = nroDepto;
        this.usuario = usuario;
        initComponents();
        buttonGroup1.add(reservaRadioButton);
        buttonGroup1.add(reservaFirmeRadioButton);
        buttonGroup1.add(ocupadoRadioButton);
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        setearMonedaPorDefecto(entityManager);
        this.frame = frame;
        fechaArriboRecibida = fechaArribo;
        fechaPartidaRecibida = fechaPartida;

        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd/MM/yyyy");
        String fecha = sdf.format(fechaArribo);
        fechaArriboField.setText(fecha);
        fecha = sdf.format(fechaPartida);
        fechaPartidaField.setText(fecha);


        unidadAlojamientoText.setText(unidadesAlojamientoQuery.getResultList().get(0).toString());
        unidadAlojamientoReservaActual = (UnidadesAlojamiento) unidadesAlojamientoQuery.getResultList().get(0);

        alquilerActual = new entities.Alquileres();
        entityManager.persist(alquilerActual);
        list.add(alquilerActual);
        setearCantidadPersonas();

        CalcularTotalAlquiler calculo = new CalcularTotalAlquiler();
        montoTotalField.setText((calculo.calcularTotal(Integer.parseInt(cantidadPersonasComboBox.getSelectedItem().toString()), fechaArriboRecibida, fechaPartidaRecibida)).toString());
        montoReservaField.setText(String.valueOf(((calculo.calcularTotal(Integer.parseInt(cantidadPersonasComboBox.getSelectedItem().toString()), fechaArriboRecibida, fechaPartidaRecibida)) * 10) / 100));
        seleccionarMonedaComboBox();
        cantidadReservasCreadas++;
    }

    private void seleccionarMonedaComboBox() {
        monedaComboBox.setSelectedItem(monedaPorDefecto);
    }

    public static void setearMonedaPorDefecto(EntityManager entityManager) {
        Query query = entityManager.createNamedQuery("Moneda.findByClave");
        query.setParameter("clave", "ARS");
        monedaPorDefecto = (Moneda) query.getSingleResult();
    }

    private Integer getIDReserva(UnidadesAlojamiento idUnidadAlojamiento, Clientes idCliente, Date fechaArribo, Date fechaPartida) {
        Query queryIDReserva;
        Alquileres reserva;
        queryIDReserva = entityManager.createNamedQuery("Alquileres.findByAll");
        queryIDReserva.setParameter("idUnidadAlojamiento", idUnidadAlojamiento);
        queryIDReserva.setParameter("idCliente", idCliente);
        queryIDReserva.setParameter("fechaArribo", fechaArribo);
        queryIDReserva.setParameter("fechaPartida", fechaPartida);
        reserva = (Alquileres) queryIDReserva.getSingleResult();
        return reserva.getIdAlquiler();
    }

    public static int getCantidadReservasCreadas() {
        return cantidadReservasCreadas;
    }

    public static void setCantidadReservasCreadas(int cantidadReservasCreadas) {
        VistaNuevaReserva.cantidadReservasCreadas = cantidadReservasCreadas;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT a FROM Alquileres a");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        unidadesAlojamientoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u WHERE u.idUnidad = :nroDep").setParameter("nroDep",nroDep);
        unidadesAlojamientoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery.getResultList();
        unidadesAlojamientoQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT u FROM UnidadesAlojamiento u");
        unidadesAlojamientoList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : unidadesAlojamientoQuery1.getResultList();
        clientesQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c  ORDER BY c.apellido");
        clientesList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery.getResultList();
        clientesQuery1 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList1 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery1.getResultList();
        buttonGroup1 = new javax.swing.ButtonGroup();
        clientesQuery2 = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c");
        clientesList2 = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : clientesQuery2.getResultList();
        monedaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT m FROM Moneda m WHERE m.activo = 'S'");
        monedaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : monedaQuery.getResultList();
        idUnidadAlojamientoLabel = new javax.swing.JLabel();
        idClienteLabel = new javax.swing.JLabel();
        tipoAlquilerLabel = new javax.swing.JLabel();
        fechaArriboLabel = new javax.swing.JLabel();
        fechaPartidaLabel = new javax.swing.JLabel();
        cantidadPersonasLabel = new javax.swing.JLabel();
        montoTotalLabel = new javax.swing.JLabel();
        montoReservaLabel = new javax.swing.JLabel();
        montoTotalField = new javax.swing.JTextField();
        montoReservaField = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();
        agregarClienteButton = new javax.swing.JButton();
        reservaRadioButton = new javax.swing.JRadioButton();
        reservaFirmeRadioButton = new javax.swing.JRadioButton();
        ocupadoRadioButton = new javax.swing.JRadioButton();
        cantidadPersonasComboBox = new javax.swing.JComboBox();
        unidadAlojamientoText = new javax.swing.JLabel();
        ayudaLabel2 = new javax.swing.JLabel();
        fechaArriboField = new javax.swing.JTextField();
        fechaPartidaField = new javax.swing.JTextField();
        agregarClienteButton1 = new javax.swing.JButton();
        clienteTextField = new javax.swing.JTextField();
        monedaComboBox = new javax.swing.JComboBox();

        FormListener formListener = new FormListener();

        idUnidadAlojamientoLabel.setText("Unidad Alojamiento:");

        idClienteLabel.setText("Cliente:");

        tipoAlquilerLabel.setText("Tipo Alquiler:");

        fechaArriboLabel.setText("Fecha Arribo:");

        fechaPartidaLabel.setText("Fecha Partida:");

        cantidadPersonasLabel.setText("Cantidad Personas:");

        montoTotalLabel.setText("Monto Total:");

        montoReservaLabel.setText("Monto Reserva:");

        montoTotalField.addKeyListener(formListener);

        montoReservaField.addKeyListener(formListener);

        saveButton.setBackground(new java.awt.Color(1, 154, 210));
        saveButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        saveButton.setForeground(new java.awt.Color(255, 255, 255));
        saveButton.setText("Generar Reserva");
        saveButton.addActionListener(formListener);

        agregarClienteButton.setBackground(new java.awt.Color(1, 154, 210));
        agregarClienteButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        agregarClienteButton.setForeground(new java.awt.Color(255, 255, 255));
        agregarClienteButton.setText("Nuevo Cliente");
        agregarClienteButton.addActionListener(formListener);

        reservaRadioButton.setSelected(true);
        reservaRadioButton.setText("Reserva");
        reservaRadioButton.addActionListener(formListener);

        reservaFirmeRadioButton.setText("Reserva Firme");
        reservaFirmeRadioButton.addActionListener(formListener);

        ocupadoRadioButton.setText("Ocupado");
        ocupadoRadioButton.addActionListener(formListener);

        cantidadPersonasComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4" }));

        unidadAlojamientoText.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

        ayudaLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N

        fechaArriboField.setEditable(false);

        fechaPartidaField.setEditable(false);

        agregarClienteButton1.setBackground(new java.awt.Color(1, 154, 210));
        agregarClienteButton1.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        agregarClienteButton1.setForeground(new java.awt.Color(255, 255, 255));
        agregarClienteButton1.setText("Seleccionar Cliente");
        agregarClienteButton1.addActionListener(formListener);

        clienteTextField.setEditable(false);
        clienteTextField.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, monedaList, monedaComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ayudaLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(saveButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(idClienteLabel)
                                .addComponent(cantidadPersonasLabel)
                                .addComponent(tipoAlquilerLabel)
                                .addComponent(fechaArriboLabel)
                                .addComponent(montoTotalLabel)
                                .addComponent(montoReservaLabel))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(26, 26, 26)
                                .addComponent(fechaPartidaLabel))
                            .addComponent(idUnidadAlojamientoLabel))
                        .addGap(6, 6, 6)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(montoReservaField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(montoTotalField, javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(cantidadPersonasComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 95, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(monedaComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(reservaRadioButton)
                                .addGap(18, 18, 18)
                                .addComponent(reservaFirmeRadioButton)
                                .addGap(18, 18, 18)
                                .addComponent(ocupadoRadioButton))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(unidadAlojamientoText, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(clienteTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 240, Short.MAX_VALUE)))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(fechaArriboField)
                                .addComponent(fechaPartidaField, javax.swing.GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)))
                        .addGap(0, 145, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(agregarClienteButton1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(agregarClienteButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(agregarClienteButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(unidadAlojamientoText, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(idUnidadAlojamientoLabel))
                    .addComponent(agregarClienteButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(idClienteLabel)
                    .addComponent(clienteTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tipoAlquilerLabel)
                    .addComponent(reservaRadioButton)
                    .addComponent(reservaFirmeRadioButton)
                    .addComponent(ocupadoRadioButton))
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaArriboLabel)
                    .addComponent(fechaArriboField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(fechaPartidaLabel)
                    .addComponent(fechaPartidaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cantidadPersonasLabel)
                    .addComponent(cantidadPersonasComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(montoTotalLabel)
                    .addComponent(montoTotalField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(montoReservaLabel)
                    .addComponent(montoReservaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(monedaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ayudaLabel2))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.KeyListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == saveButton) {
                VistaNuevaReserva.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == agregarClienteButton) {
                VistaNuevaReserva.this.agregarClienteButtonActionPerformed(evt);
            }
            else if (evt.getSource() == reservaRadioButton) {
                VistaNuevaReserva.this.reservaRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == reservaFirmeRadioButton) {
                VistaNuevaReserva.this.reservaFirmeRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == ocupadoRadioButton) {
                VistaNuevaReserva.this.ocupadoRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == agregarClienteButton1) {
                VistaNuevaReserva.this.agregarClienteButton1ActionPerformed(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == montoTotalField) {
                VistaNuevaReserva.this.montoTotalFieldKeyTyped(evt);
            }
            else if (evt.getSource() == montoReservaField) {
                VistaNuevaReserva.this.montoReservaFieldKeyTyped(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private String identificarTipoAlquiler(String tipoAlquiler) {
        switch (tipoAlquiler) {
            case "O":
                return "Un Alquiler Ocupado";
            case "F":
                return "Una Reserva Firme";
            default:
                return "Una Reserva";
        }
    }

    private String formatearFecha(Date fecha) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(fecha);
        String salida = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR) + " a las " + cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE);
        return salida;
    }

    public static String identificarReferencia(Alquileres alquiler) {
        String referencia = "";
        switch (alquiler.getTipoAlquiler()) {
            case "F":
                referencia = "Alquiler";
                break;
            case "R":
                referencia = "Reserva";
                break;
            case "O":
                referencia = "Alquiler";
                break;
        }
        return referencia;
    }

    public static Integer identificarOperacion(EntityManager entityManager, Double montoReserva) {
        Query queryOperacion = entityManager.createNamedQuery("Operaciones.findByOperacion");
        Operaciones operacion;
        if (montoReserva.equals(Double.valueOf("0.0"))) {
            queryOperacion.setParameter("operacion", "RESERVA");
        } else {
            queryOperacion.setParameter("operacion", "ALQUILER");
        }
        operacion = (Operaciones) queryOperacion.getSingleResult();
        return operacion.getId();
    }

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        String montoReservastr = montoReservaField.getText();
        String montoTotalstr = montoTotalField.getText();
        Caja movCaja = new Caja();
        Moneda monedaActual = (Moneda) monedaComboBox.getSelectedItem();

        if (("".equals(montoTotalField.getText()))) {
            JOptionPane.showMessageDialog(this, "El Monto Total no puede ser vacio", "Atencion", JOptionPane.ERROR_MESSAGE, null);
            montoTotalField.requestFocus();
        } else if (("".equals(clienteTextField.getText()))) {
            JOptionPane.showMessageDialog(this, "Debe buscar un cliente o dar de alta uno", "Atencion", JOptionPane.ERROR_MESSAGE, null);

        } else {
            try {
                logs = new Logs();
                logs.setUsuario(usuario);
                alquilerActual.setIdUnidadAlojamiento(((UnidadesAlojamiento) unidadesAlojamientoList.get(0)));
                alquilerActual.setIdCliente(cliente);
                alquilerActual.setFechaArribo(fechaArriboRecibida);
                alquilerActual.setFechaPartida(fechaPartidaRecibida);
                alquilerActual.setCantidadPersonas(Integer.parseInt(cantidadPersonasComboBox.getSelectedItem().toString()));
                Double montoReserva;
                alquilerActual.setMontoReserva(Double.parseDouble("".equals(montoReservaField.getText()) ? "0" : montoReservastr));
                if (!(alquilerActual.getMontoReserva().compareTo(0.0) <= 0)){
                    montoReserva = alquilerActual.getMontoReserva()*monedaActual.getCambio();
                    alquilerActual.setMontoReserva(montoReserva);
                }
                alquilerActual.setMontoTotal(Double.parseDouble("".equals(montoTotalField.getText()) ? "0" : montoTotalstr));
                alquilerActual.setTipoAlquiler(tipoAlquiler);
                if (alquilerActual.getMontoReserva().equals(Double.valueOf("0.0"))) {
                    alquilerActual.setTipoAlquiler("R");
                } else {
                    if (alquilerActual.getTipoAlquiler().equals("R")) {
                        alquilerActual.setTipoAlquiler("F");
                    }
                }
                if (alquilerActual.getIdAlquiler() == null) {
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                    Integer idReserva = getIDReserva(alquilerActual.getIdUnidadAlojamiento(), alquilerActual.getIdCliente(), alquilerActual.getFechaArribo(), alquilerActual.getFechaPartida());
                    logs.setearObservaciones("Alta", "Reservas", idReserva, "VistaNuevaReserva");
                    if (alquilerActual.getMontoReserva().compareTo(Double.valueOf("0.0")) > 0) {
                        movCaja.setFecha(new Date());
                        movCaja.setImporte(Double.valueOf(montoReservaField.getText()));
                        movCaja.setMoneda(monedaActual.getClave());
                        movCaja.setObservaciones(identificarReferencia(alquilerActual) + "ID: " + alquilerActual.getIdAlquiler());
                        movCaja.setOperacion(identificarOperacion(entityManager, alquilerActual.getMontoReserva().doubleValue()));
                        movCaja.setResponsable(usuario.getIdUsuario());
                        entityManager.persist(movCaja);
                    }
                } else {
                    logs.setearObservaciones("Modificación", "Reservas", alquilerActual.getIdAlquiler(), "VistaNuevaReserva");
                }
                entityManager.persist(logs);
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
                if (!"".equals(cliente.getEmail())) {
                    int i = JOptionPane.showConfirmDialog(this, "Desea enviar mail de confirmación de reserva al cliente?", "Enviar e-mail", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                    if (i == 0) {

                        //Busqueda de datos de configuración
                        ConfiguracionMail configMail = entityManager.find(ConfiguracionMail.class, 1);

                        //Envio mail de confirmación
                        Date llegadaCalendar = fechaArriboRecibida;
                        Date partidaCalendar = fechaPartidaRecibida;
                        String codigo = String.valueOf(alquilerActual.getIdAlquiler());
                        String llegada = String.valueOf(llegadaCalendar.getDate()) + "/" + String.valueOf(llegadaCalendar.getMonth() + 1) + "/" + String.valueOf(llegadaCalendar.getYear() + 1900);
                        String partida = String.valueOf(partidaCalendar.getDate()) + "/" + String.valueOf(partidaCalendar.getMonth() + 1) + "/" + String.valueOf(partidaCalendar.getYear() + 1900);

                        String smtpHost = configMail.getSmtpHostmail();
                        Integer port = configMail.getPortMail();
                        String fromMail = configMail.getFromMail();
                        String user = configMail.getUserMail();
                        String pass = configMail.getPassMail();

                        String toMail = cliente.getEmail().toString();
                        String textMail = "CONFIRMACION DE RESERVA\n\nNombre y Apellido: " + cliente.getNombres() + " " + cliente.getApellido()
                                + "\nCodigo de Reserva: " + codigo
                                + "\nCheck-in: " + llegada
                                + "\nCheck-out: " + partida
                                + "\nCantidad de Personas: " + cantidadPersonasComboBox.getSelectedItem().toString()
                                + "\nSe aloja en: " + unidadAlojamientoText.getText().toString()
                                + "\nTotal del Alquiler: $" + montoTotalField.getText().toString();

                        MailSender mailSender = new MailSender();
                        mailSender.sendEmail(smtpHost, port, fromMail, user, pass, toMail, textMail);
                    }
                }
                cantidadReservasCreadas--;
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<entities.Alquileres> merged = new ArrayList<entities.Alquileres>(list.size());
                for (entities.Alquileres a : list) {
                    merged.add(entityManager.merge(a));
                }
                list.clear();
                list.addAll(merged);
            }
            VistaDisponibilidad.botonDiaHoy.doClick();
            VistaDisponibilidad.resetear(entityManager);
            this.frame.dispose();
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    public void setearCantidadPersonas() {
        cantidadPersonasComboBox.removeAllItems();
        Integer cant;
        for (int i = 1; i <= unidadAlojamientoReservaActual.getCapacidad(); i++) {
            cant = new Integer(i);
            cantidadPersonasComboBox.addItem(cant);
        }
    }

    private void reservaRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reservaRadioButtonActionPerformed
        tipoAlquiler = "R";
    }//GEN-LAST:event_reservaRadioButtonActionPerformed
    public static void setearCliente(Clientes clienteRecibido) {
        cliente = clienteRecibido;
        clienteTextField.setText(cliente.getApellido() + " " + cliente.getNombres());
    }
    private void agregarClienteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarClienteButtonActionPerformed
        AltaClienteReserva nuevocliente = new AltaClienteReserva(usuario, null, false);
        nuevocliente.main(usuario, false);
    }//GEN-LAST:event_agregarClienteButtonActionPerformed

    private void reservaFirmeRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reservaFirmeRadioButtonActionPerformed
        tipoAlquiler = "F";
    }//GEN-LAST:event_reservaFirmeRadioButtonActionPerformed

    private void ocupadoRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ocupadoRadioButtonActionPerformed
        tipoAlquiler = "O";
    }//GEN-LAST:event_ocupadoRadioButtonActionPerformed

    private void montoTotalFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_montoTotalFieldKeyTyped
        char caracter = evt.getKeyChar();

        // Verificar si la tecla pulsada no es un digito
        if (((caracter < '0')
                || (caracter > '9'))
                && (caracter != '\b' /*
                 * corresponde a BACK_SPACE
                 */)) {
            evt.consume();  // ignorar el evento de teclado
        }       // TODO add your handling code here:
        // TODO add your handling code here:
    }//GEN-LAST:event_montoTotalFieldKeyTyped

    private void montoReservaFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_montoReservaFieldKeyTyped
        char caracter = evt.getKeyChar();

        // Verificar si la tecla pulsada no es un digito
        if (((caracter < '0')
                || (caracter > '9'))
                && (caracter != '\b' /*
                 * corresponde a BACK_SPACE
                 */)) {
            evt.consume();  // ignorar el evento de teclado
        }       // TODO add your handling code here:
        // TODO add your handling code here:
    }//GEN-LAST:event_montoReservaFieldKeyTyped

    private void agregarClienteButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_agregarClienteButton1ActionPerformed
        BusquedaCliente buscarCliente = new BusquedaCliente(null, false);
        buscarCliente.main(false);
    }//GEN-LAST:event_agregarClienteButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton agregarClienteButton;
    private javax.swing.JButton agregarClienteButton1;
    private javax.swing.JLabel ayudaLabel2;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cantidadPersonasComboBox;
    private javax.swing.JLabel cantidadPersonasLabel;
    private static javax.swing.JTextField clienteTextField;
    private java.util.List<entities.Clientes> clientesList;
    private java.util.List<entities.Clientes> clientesList1;
    private java.util.List<entities.Clientes> clientesList2;
    private javax.persistence.Query clientesQuery;
    private javax.persistence.Query clientesQuery1;
    private javax.persistence.Query clientesQuery2;
    private static javax.persistence.EntityManager entityManager;
    private javax.swing.JTextField fechaArriboField;
    private javax.swing.JLabel fechaArriboLabel;
    private javax.swing.JTextField fechaPartidaField;
    private javax.swing.JLabel fechaPartidaLabel;
    private javax.swing.JLabel idClienteLabel;
    private javax.swing.JLabel idUnidadAlojamientoLabel;
    private java.util.List<entities.Alquileres> list;
    private javax.swing.JComboBox monedaComboBox;
    private java.util.List<entities.Moneda> monedaList;
    private javax.persistence.Query monedaQuery;
    private javax.swing.JTextField montoReservaField;
    private javax.swing.JLabel montoReservaLabel;
    private javax.swing.JTextField montoTotalField;
    private javax.swing.JLabel montoTotalLabel;
    private javax.swing.JRadioButton ocupadoRadioButton;
    private javax.persistence.Query query;
    private javax.swing.JRadioButton reservaFirmeRadioButton;
    private javax.swing.JRadioButton reservaRadioButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JLabel tipoAlquilerLabel;
    private javax.swing.JLabel unidadAlojamientoText;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList;
    private java.util.List<entities.UnidadesAlojamiento> unidadesAlojamientoList1;
    private javax.persistence.Query unidadesAlojamientoQuery;
    private javax.persistence.Query unidadesAlojamientoQuery1;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(Integer nrodepto, Date fechaarribo, Date fechapartida, Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaNuevaReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaNuevaReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaNuevaReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaNuevaReserva.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        final Integer nroDepto = nrodepto;
        final Date fechaArribo = fechaarribo;
        final Date fechaPartida = fechapartida;
        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame();
                VistaNuevaReserva abmreservas = new VistaNuevaReserva(nroDepto, fechaArribo, fechaPartida, frame, usuario);
                frame.setContentPane(abmreservas);
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Reserva   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        VistaNuevaReserva.setCantidadReservasCreadas(VistaNuevaReserva.getCantidadReservasCreadas() - 1);
                    }
                });
            }
        });
    }
}
